/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 28779
 * Date: 2023-09-01
 * Time: 12:40
 */
//懒汉模式

    /*重点
    * 1.加锁
    * 2.双重if
    * 3.加 volatile
    * */
class SingletonLazy {
    public static volatile SingletonLazy instance  = null;
    private static Object locker = new Object();
    public static SingletonLazy getInstance() {
        //instacne 如果为 null,说明是首次调用,就需要加锁.如果非 null, 就说明是后续调用, 就不用加锁了.
        if (instance == null) {
            //这里可以用 SingletonLazy 的类对象进行加锁,也可以用新建的 locker 来加锁.
            synchronized (SingletonLazy.class) {
                if (instance == null) {
                    instance = new SingletonLazy();
                }
            }
        }
        return instance;
    }
    private SingletonLazy() {}

}
public class Demo2 {
    public static void main(String[] args) {
        SingletonLazy s1 = SingletonLazy.getInstance();
        SingletonLazy s2 = SingletonLazy.getInstance();
        //SingletonLazy singletonLazy2 = new SingletonLazy();

        System.out.println(s1 == s2);
    }
}
